package xcmg.device.service.warehouse.allot;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.dao.entity.warehouse.allot.RegionAllotPlanDO;
import xcmg.device.dao.entity.warehouse.allot.RegionAllotPlanDetailDO;
import xcmg.device.dao.mapper.warehouse.RegionAllotDetailMapper;
import xcmg.device.dao.mapper.warehouse.RegionAllotPlanMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDOMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.infra.enums.ReginAllotPlanStatusEnum;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.vo.permission.WareHousePermission;
import xcmg.device.service.vo.warehouse.allot.RegionAllotAmountVO;
import xcmg.device.service.vo.warehouse.app.EnableAndOccupyVO;
import xcmg.device.service.warehouse.CommonService;
import xcmg.device.service.warehouse.DepartmentWarehouseRelationService;
import xcmg.device.service.warehouse.WarehouseInventoryService;
import xcmg.device.service.warehouse.allot.vo.RegionAllotPlanDetailVO;
import xcmg.device.service.warehouse.allot.vo.RegionAllotPlanVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 区域调拨计划 后台接口实现类
 */
@Slf4j
@Service
public class RegionAllotPlanService {

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RegionAllotPlanMapper regionAllotPlanMapper;

    @Autowired
    private WarehouseDOMapper warehouseDOMapper;

    @Autowired
    private RegionAllotDetailMapper regionAllotDetailMapper;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private RegionAllotPlanDetailService regionAllotPlanDetailService;

    @Autowired
    private WarehouseInventoryService warehouseInventoryService;
    @Autowired
    private DepartmentWarehouseRelationService relationService;

    @Autowired
    private FastGenClient fastGenClient;

    public PageCommonVO<RegionAllotPlanVO> list(SearchCommonVO<RegionAllotPlanVO> condition, boolean includDetail,String deptId) {
        PageCommonVO<RegionAllotPlanVO> pageCommonVO = new PageCommonVO();
        // 判断当前登陆的用户所属组织机构是否有配置仓库，如果开启了仓库控制并配置了仓库，则需要把配置的仓库加入到查询的限制条件
        WareHousePermission wareHousePermission = relationService.wareHouseChoicePermit(condition.getFilters().getOrgId(), deptId);
        if (!wareHousePermission.isHasPermission()) {
            pageCommonVO.setPageInfo(new PageInfo(new ArrayList()));
            pageCommonVO.setPageInfoList(new ArrayList<>());
            return pageCommonVO;
        } else {
            condition.getFilters().setWarehousePermitList(wareHousePermission.getPermissionWarehouses());
        }
        PageHelperPlus.orderBy("ID desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<RegionAllotPlanDO> doList = regionAllotPlanMapper.list(condition.getFilters());
        List<RegionAllotPlanVO> voList = null;
        if (includDetail) {
            voList = getVoListWithDetail(doList);
        } else {
            voList = BeanUtil.do2bo4List(doList, RegionAllotPlanVO.class);
            for (RegionAllotPlanVO vvo : voList) {
                if (StringUtils.isNotBlank(vvo.getInWarehouse())) {
                    WarehouseDO warehouse = warehouseDOMapper.itemByWarehouseCode(vvo.getOrgId(), vvo.getInWarehouse());
                    if (null != warehouse) {
                        vvo.setInWarehouseDesc(warehouse.getDescription());
                    }
                }
                if (StringUtils.isNotBlank(vvo.getOutWarehouse())) {
                    WarehouseDO warehouse = warehouseDOMapper.itemByWarehouseCode(vvo.getOrgId(), vvo.getOutWarehouse());
                    if (null != warehouse) {
                        vvo.setOutWarehouseDesc(warehouse.getDescription());
                    }
                }
            }
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public RegionAllotPlanVO queryById(String id, String orgId) {
        RegionAllotPlanVO vo = RegionAllotPlanVO.builder().id(id).isDel(0).orgId(orgId).build();
        List<RegionAllotPlanDO> ll = regionAllotPlanMapper.queryList(vo);
        List<RegionAllotPlanVO> voListWithDetail = getVoListWithDetail(ll);
        if (CollectionUtils.isNotEmpty(voListWithDetail)) {
            return voListWithDetail.get(0);
        }
        return null;
    }

    private List<RegionAllotPlanVO> getVoListWithDetail(List<RegionAllotPlanDO> ll) {
        if (CollectionUtils.isNotEmpty(ll)) {
            List<RegionAllotPlanVO> result = new ArrayList<>(ll.size());
            for (RegionAllotPlanDO ddo : ll) {
                RegionAllotPlanVO vo = BeanUtil.do2bo(ddo, RegionAllotPlanVO.class);
                if (StringUtils.isNotBlank(vo.getInWarehouse())) {
                    WarehouseDO warehouse = warehouseDOMapper.itemByWarehouseCode(ddo.getOrgId(), vo.getInWarehouse());
                    if (null != warehouse) {
                        vo.setInWarehouseDesc(warehouse.getDescription());
                    }
                }
                if (StringUtils.isNotBlank(vo.getOutWarehouse())) {
                    WarehouseDO warehouse = warehouseDOMapper.itemByWarehouseCode(ddo.getOrgId(), vo.getOutWarehouse());
                    if (null != warehouse) {
                        vo.setOutWarehouseDesc(warehouse.getDescription());
                    }
                }
                List<RegionAllotPlanDetailVO> detailVOList = regionAllotPlanDetailService.queryByFK(ddo.getId());
                //过滤计划调拨数量大于0的
                //detailVOList = detailVOList.stream().filter(o->o.getPlanAmount().subtract(o.getAllotAmount()).compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
                processDetailVoList(detailVOList, ddo);
                vo.setDetailVOList(detailVOList);
                result.add(vo);
            }
            return result;
        }
        return null;
    }

    private void processDetailVoList(List<RegionAllotPlanDetailVO> detailVOList, RegionAllotPlanDO mvo) {
        for (RegionAllotPlanDetailVO vo : detailVOList) {
            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum(vo.getMaterialNo(), vo.getOrgId(), mvo.getOutWarehouse());
            vo.setEnableNum(enableAndOccupyVO.getEnableNum());
            vo.setIntentionNum(enableAndOccupyVO.getIntentionNum());
            vo.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());
        }
    }

    public RegionAllotPlanVO queryByAllotPlanOrder(String allotPlanOrder, String orgId) {
        RegionAllotPlanVO vo = RegionAllotPlanVO.builder().allotPlanOrder(allotPlanOrder).isDel(0).orgId(orgId).build();
        List<RegionAllotPlanDO> ll = regionAllotPlanMapper.queryList(vo);
        List<RegionAllotPlanVO> voListWithDetail = getVoListWithDetail(ll);
        if (CollectionUtils.isNotEmpty(voListWithDetail)) {
            return voListWithDetail.get(0);
        }
        return null;
    }

    //保存或者提交
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(RegionAllotPlanVO regionAllotPlanVO, String userId, String orgId, Integer planStatus) throws Exception {
        ActionResult<String> textResult = null;
//        if (StringUtils.isBlank(regionAllotPlanVO.getDept()) || StringUtils.isBlank(regionAllotPlanVO.getDeptId())) {
//            log.warn("获取部门信息 error，{}", regionAllotPlanVO);
//            return ErrorCode.IllegalArument;
//        }
        if (ReginAllotPlanStatusEnum.submit.getCode() == planStatus.intValue()) {
            if (StringUtils.isBlank(regionAllotPlanVO.getInWarehouse())
                    || StringUtils.isBlank(regionAllotPlanVO.getOutWarehouse())) {
                log.warn("提交时候出入仓库信息 error，{}", regionAllotPlanVO);
                return ErrorCode.IllegalArument;
            }
        }
        List<RegionAllotPlanDetailVO> detailVOList = regionAllotPlanVO.getDetailVOList();
        if (ListUtil.isNullOrEmpty(detailVOList)) {
            return ErrorCode.MaterialsIsNull;
        }
        //校验行信息数据是否合法
        for (RegionAllotPlanDetailVO detailVO : detailVOList) {
            if (ReginAllotPlanStatusEnum.submit.getCode() == planStatus.intValue()) {
                if (detailVO.getPlanAmount() == null || detailVO.getPlanAmount().compareTo(BigDecimal.ZERO) <= 0) {
                    return ErrorCode.MaterialsNumError;
                }
            }
        }
        regionAllotPlanVO.setOrgId(orgId);
        regionAllotPlanVO.setIsDel(0);
        regionAllotPlanVO.setPlanStatus(planStatus);
        if (StringUtils.isBlank(regionAllotPlanVO.getId())) {
            textResult = fastGenClient.textGuid();
            if (textResult.getCode() != ErrorCode.Success.getCode()) {
                log.warn("获取textGuid error，{}", regionAllotPlanVO);
                return ErrorCode.IllegalArument;
            }
            regionAllotPlanVO.setId(textResult.getValue());
            regionAllotPlanVO.setAllotPlanOrder(genDocumentService.genDocumentNo(BillDesc.RegionAllotPlan, orgId));
            regionAllotPlanVO.setCreateId(userId);
            regionAllotPlanVO.setCreateName(commonService.getUserName(userId));
            regionAllotPlanVO.setCreateDate(new Date());
            //新增
            regionAllotPlanMapper.insert(BeanUtil.do2bo(regionAllotPlanVO, RegionAllotPlanDO.class));
        } else {
            RegionAllotPlanVO vo = queryById(regionAllotPlanVO.getId(), orgId);
            if (null == vo) {
                log.warn("根据id查询 error，{}", regionAllotPlanVO);
                return ErrorCode.IllegalArument;
            }
            if (vo.getPlanStatus().intValue() != ReginAllotPlanStatusEnum.save.getCode()) {
                log.warn("查询单据不允许修改 error，{}", regionAllotPlanVO);
                return ErrorCode.RegionAllotPlan;
            }
            regionAllotPlanMapper.updateByPrimaryKeySelective(BeanUtil.do2bo(regionAllotPlanVO, RegionAllotPlanDO.class));
        }

        for (RegionAllotPlanDetailVO detailVO : detailVOList) {
            textResult = fastGenClient.textGuid();
            if (textResult.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("系统异常：生产ID失败");
            }
            detailVO.setId(textResult.getValue());
            detailVO.setAllotPlanOrder(regionAllotPlanVO.getAllotPlanOrder());
            detailVO.setHeaderId(regionAllotPlanVO.getId());
            detailVO.setOrgId(regionAllotPlanVO.getOrgId());
            detailVO.setCreateDate(regionAllotPlanVO.getCreateDate());
            detailVO.setCreateId(regionAllotPlanVO.getCreateId());
            detailVO.setCreateName(regionAllotPlanVO.getCreateName());
            detailVO.setPlanStatus(regionAllotPlanVO.getPlanStatus());
            detailVO.setAllotAmount(BigDecimal.ZERO);
        }
        regionAllotPlanDetailService.deleteByFK(regionAllotPlanVO.getId());
        regionAllotPlanDetailService.batchAdd(BeanUtil.do2bo4List(detailVOList, RegionAllotPlanDetailDO.class));
        return ErrorCode.Success;
    }

    @Transactional
    public ErrorCode manuFinish(ArrayList<String> ids, String orgId) {
        for (String id : ids) {
            RegionAllotPlanVO vo = queryById(id, orgId);
            if (null == vo) {
                log.warn("根据id查询 error，{}", vo);
                throw new RuntimeException(ErrorCode.IllegalArument.getDesc());
            }
            if (!ReginAllotPlanStatusEnum.canNanuFinishStatus(vo.getPlanStatus())) {
                throw new RuntimeException(ErrorCode.RegionAllotPlanCantnotEnd.getDesc());
            }
            RegionAllotPlanDO regionAllotPlanDO = new RegionAllotPlanDO();
            regionAllotPlanDO.setId(id);
            regionAllotPlanDO.setPlanStatus(ReginAllotPlanStatusEnum.endBill.getCode());
            regionAllotPlanMapper.updateByPrimaryKeySelective(regionAllotPlanDO);
            for (RegionAllotPlanDetailVO vvo : vo.getDetailVOList()) {
                if (vvo.getPlanStatus() != ReginAllotPlanStatusEnum.done.getCode()) {
                    RegionAllotPlanDetailDO ddo = new RegionAllotPlanDetailDO();
                    ddo.setId(vvo.getId());
                    ddo.setPlanStatus(ReginAllotPlanStatusEnum.endBill.getCode());
                    regionAllotPlanDetailService.update(ddo);
                }
            }
        }
        return ErrorCode.Success;
    }

    @Transactional
    public ErrorCode manuFinishByDetailIds(ArrayList<String> detailIds, String orgId) {
        List<RegionAllotPlanDetailDO> detailDOList = regionAllotPlanDetailService.queryListByIds(detailIds);
        if (CollectionUtils.isEmpty(detailDOList)) {
            return ErrorCode.IllegalArument;
        }
        String headerId = detailDOList.get(0).getHeaderId();
        for (RegionAllotPlanDetailDO ddo : detailDOList) {
            if (!headerId.equals(ddo.getHeaderId())) {
                log.warn("非相同调拨申请表数据");
                return ErrorCode.IllegalArument;
            }
            if (!ReginAllotPlanStatusEnum.canNanuFinishStatus(ddo.getPlanStatus())) {
                return ErrorCode.RegionAllotPlanCantnotEnd;
            }
        }
        for (RegionAllotPlanDetailDO ddo : detailDOList) {
            RegionAllotPlanDetailDO detailDO = new RegionAllotPlanDetailDO();
            detailDO.setId(ddo.getId());
            detailDO.setPlanStatus(ReginAllotPlanStatusEnum.endBill.getCode());
            regionAllotPlanDetailService.update(detailDO);
        }
        RegionAllotPlanVO vo = queryById(headerId, orgId);
        //根据子表状态信息更新主表信息
        updateHeaderPlanstatus(vo);
        return ErrorCode.Success;
    }

    private void updateHeaderPlanstatus(RegionAllotPlanVO vo) {
        if (CollectionUtils.isEmpty(vo.getDetailVOList())) {
            return;
        }
        int headerPlanStatus = vo.getPlanStatus();
        int size = vo.getDetailVOList().size();
        //结单的子表提交数量
        int submitCount = 0;
        //部分完成的字表数量
        int partCount = 0;
        //完成的子表数量
        int doneCount = 0;
        //结单的子表数量
        int endBillCount = 0;

        for (RegionAllotPlanDetailVO vvo : vo.getDetailVOList()) {
            if (vvo.getPlanStatus().intValue() == ReginAllotPlanStatusEnum.save.getCode()) {
                headerPlanStatus = ReginAllotPlanStatusEnum.save.getCode();
                break;
            }
            if (vvo.getPlanStatus().intValue() == ReginAllotPlanStatusEnum.submit.getCode()) {
                submitCount++;
                continue;
            }
            if (vvo.getPlanStatus().intValue() == ReginAllotPlanStatusEnum.part.getCode()) {
                headerPlanStatus = ReginAllotPlanStatusEnum.part.getCode();
                partCount++;
                continue;
            }
            if (vvo.getPlanStatus().intValue() == ReginAllotPlanStatusEnum.done.getCode()) {
                headerPlanStatus = ReginAllotPlanStatusEnum.part.getCode();
                doneCount++;
                continue;
            }
            if (vvo.getPlanStatus().intValue() == ReginAllotPlanStatusEnum.endBill.getCode()) {
                endBillCount++;
                continue;
            }
        }
        if (submitCount == size) {
            headerPlanStatus = ReginAllotPlanStatusEnum.submit.getCode();
        } else if (endBillCount == size) {
            headerPlanStatus = ReginAllotPlanStatusEnum.endBill.getCode();
        } else if (doneCount == size) {
            headerPlanStatus = ReginAllotPlanStatusEnum.done.getCode();
        } else if (submitCount + endBillCount == size) {
            headerPlanStatus = ReginAllotPlanStatusEnum.submit.getCode();
        } else if ((doneCount + endBillCount) == size) {
            headerPlanStatus = ReginAllotPlanStatusEnum.endBill.getCode();
        }
        if (vo.getPlanStatus().intValue() != headerPlanStatus) {
            RegionAllotPlanDO regionAllotPlanDO = new RegionAllotPlanDO();
            regionAllotPlanDO.setId(vo.getId());
            regionAllotPlanDO.setPlanStatus(headerPlanStatus);
            regionAllotPlanMapper.updateByPrimaryKeySelective(regionAllotPlanDO);
        }
    }

    @Transactional
    public ErrorCode delete(ArrayList<String> ids, String orgId) {
        for (String id : ids) {
            RegionAllotPlanVO vo = queryById(id, orgId);
            if (null == vo) {
                log.warn("根据id查询 error，{}", vo);
                throw new RuntimeException(ErrorCode.IllegalArument.getDesc());
            }
            if (ReginAllotPlanStatusEnum.save.getCode() != vo.getPlanStatus().intValue()) {
                throw new RuntimeException(ErrorCode.RegionAllotPlanCantnotDel.getDesc());
            }
            regionAllotPlanDetailService.deleteByFK(id);
            RegionAllotPlanDO regionAllotPlanDO = new RegionAllotPlanDO();
            regionAllotPlanDO.setId(id);
            regionAllotPlanDO.setIsDel(1);
            regionAllotPlanMapper.updateByPrimaryKeySelective(regionAllotPlanDO);
        }
        return ErrorCode.Success;
    }


    @Transactional
    public ErrorCode updatePlanstatus(String id, String orgId) {
        RegionAllotPlanVO vo = queryById(id, orgId);
        if (null == vo && CollectionUtils.isEmpty(vo.getDetailVOList())) {
            throw new RuntimeException("参数异常，数据不存在");
        }
        if (vo.getPlanStatus().intValue() == ReginAllotPlanStatusEnum.save.getCode()) {
            throw new RuntimeException("参数异常，计划状态不允许");
        }
        Set<String> materialSet = new HashSet<>();
        for (RegionAllotPlanDetailVO detailVO : vo.getDetailVOList()) {
            materialSet.add(detailVO.getMaterialNo());
        }
        //获取各个零件的执行数量
        List<RegionAllotAmountVO> list = regionAllotDetailMapper.countAllotAmountByMaterialsNos(id, new ArrayList<String>(materialSet));
        Map<String, BigDecimal> materialAmount = list.stream().collect(Collectors.toMap(RegionAllotAmountVO::getMaterialsNo, RegionAllotAmountVO::getAmount));
        //处理每个子单据的状态和已经执行数量,同时也处理vo中的信息
        for (RegionAllotPlanDetailVO detailVO : vo.getDetailVOList()) {
            materialSet.add(detailVO.getMaterialNo());
            BigDecimal amount = materialAmount.get(detailVO.getMaterialNo());
            if (null == amount) {
                amount = BigDecimal.ZERO;
            }
            if (detailVO.getPlanAmount().compareTo(amount) < 0) {
                throw new RuntimeException("零件：" + detailVO.getMaterialNo() + "执行数量超过计划数量");
            }
            if (detailVO.getPlanAmount().compareTo(amount) == 0) {
                detailVO.setPlanStatus(ReginAllotPlanStatusEnum.done.getCode());
            } else if (ReginAllotPlanStatusEnum.endBill.getCode() == detailVO.getPlanStatus().intValue()) {
                if (detailVO.getAllotAmount().compareTo(amount) < 0) {
                    throw new RuntimeException("零件：" + detailVO.getMaterialNo() + "已结单不允许新增");
                }
            } else if (amount.compareTo(BigDecimal.ZERO) > 0) {
                detailVO.setPlanStatus(ReginAllotPlanStatusEnum.part.getCode());
            }
            detailVO.setAllotAmount(amount);

            RegionAllotPlanDetailDO ddo = new RegionAllotPlanDetailDO();
            ddo.setId(detailVO.getId());
            ddo.setAllotAmount(detailVO.getAllotAmount());
            ddo.setPlanStatus(detailVO.getPlanStatus());
            regionAllotPlanDetailService.update(ddo);
        }
        updateHeaderPlanstatus(vo);
        return ErrorCode.Success;
    }

    public void exportAll(RegionAllotPlanVO condition,String deptId) throws Exception {
        // 判断当前登陆的用户所属组织机构是否有配置仓库，如果开启了仓库控制并配置了仓库，则需要把配置的仓库加入到查询的限制条件
        WareHousePermission wareHousePermission = relationService.wareHouseChoicePermit(condition.getOrgId(), deptId);
        if(!wareHousePermission.isHasPermission()){
            invokeExport(Collections.EMPTY_LIST);
        }else {
            condition.setWarehousePermitList(wareHousePermission.getPermissionWarehouses());
        }
        Integer count = regionAllotPlanMapper.findCountForExportAll(condition);
        List<RegionAllotPlanVO> dataList = new ArrayList<>();
        int times = count / 500 + 1;
        Map<String, String> warehouseCache = new HashMap<>();
        for (int i = 0; i < times; i++) {
            PageHelperPlus.startPage(i + 1, 500, "ID desc");
            List<RegionAllotPlanDO> doList = regionAllotPlanMapper.list(condition);
            if (CollectionUtils.isNotEmpty(doList)) {
                List<RegionAllotPlanVO> voList = getVoListWithDetail(doList);
                dataList.addAll(voList);
            }
        }
        invokeExport(dataList);
    }

    private void invokeExport(List<RegionAllotPlanVO> volist) throws Exception {
        String title = "区域调拨计划单数据导出";
        String[] rowsName = new String[]{"序号", "调拨计划单号", "制单部门", "制单人", "制单时间", "调出仓库",
                "调出仓库描述", "调入仓库", "调入仓库描述", "收货人", "收货人联系方式",
                "收货地址", "移动类型", "状态",
                "零件编码", "零件名称", "单位", "实际库存", "意向占用",
                "发货占用", "申请数量", "已创建区域调拨单数量", "零件行状态", "备注"};
        int i = 1;
        List<Object[]> dataList = new ArrayList<Object[]>();
        for (RegionAllotPlanVO vo : volist) {
            if (CollectionUtils.isNotEmpty(vo.getDetailVOList())) {
                for (RegionAllotPlanDetailVO detailVO : vo.getDetailVOList()) {
                    Object[] obj = new Object[rowsName.length];
                    obj[0] = i;
                    obj[1] = vo.getAllotPlanOrder();
                    obj[2] = vo.getDept();
                    obj[3] = vo.getCreateName();
                    obj[4] = DateUtil.formatDateTime(vo.getCreateDate());
                    obj[5] = vo.getOutWarehouse();
                    obj[6] = vo.getOutWarehouseDesc();
                    obj[7] = vo.getInWarehouse();
                    obj[8] = vo.getInWarehouseDesc();
                    obj[9] = vo.getReceiveUser();
                    obj[10] = vo.getReceiveTel();
                    obj[11] = vo.getReceiveAddress();
                    obj[12] = vo.getMoveType();
                    obj[13] = ReginAllotPlanStatusEnum.getDescByCode(vo.getPlanStatus());
                    obj[14] = detailVO.getMaterialNo();
                    obj[15] = detailVO.getMaterialName();
                    obj[16] = detailVO.getUnit();
                    obj[17] = detailVO.getEnableNum();
                    obj[18] = detailVO.getIntentionNum();
                    obj[19] = detailVO.getDeliveryNum();
                    obj[20] = detailVO.getPlanAmount();
                    obj[21] = detailVO.getAllotAmount();
                    obj[22] = ReginAllotPlanStatusEnum.getDescByCode(detailVO.getPlanStatus());
                    obj[23] = detailVO.getRemark();
                    dataList.add(obj);
                    i++;
                }
            } else {
                log.warn("没有明细记录，{}", vo);
            }
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }


    //保存或者提交
    @Transactional(rollbackFor = Exception.class)
    public String add4External(RegionAllotPlanVO regionAllotPlanVO, String userId, String orgId, Integer planStatus) throws Exception {
        String sapCode = regionAllotPlanVO.getSapCode();
        ActionResult<String> textResult = null;
        if (ReginAllotPlanStatusEnum.submit.getCode() == planStatus.intValue()) {
            if (StringUtils.isBlank(regionAllotPlanVO.getInWarehouse())
                    || StringUtils.isBlank(regionAllotPlanVO.getOutWarehouse())) {
                log.warn("提交时候出入仓库信息 error，{}", regionAllotPlanVO);
                throw new Exception("提交时候出入仓库信息出错");
            }
        }
        List<RegionAllotPlanDetailVO> detailVOList = regionAllotPlanVO.getDetailVOList();
        if (ListUtil.isNullOrEmpty(detailVOList)) {
            throw new Exception("零件详情不能为空");
        }
        //校验行信息数据是否合法
        for (RegionAllotPlanDetailVO detailVO : detailVOList) {
            if (ReginAllotPlanStatusEnum.submit.getCode() == planStatus.intValue()) {
                if (detailVO.getPlanAmount() == null || detailVO.getPlanAmount().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new Exception("申请数量不正确");
                }
            }
        }
        regionAllotPlanVO.setOrgId(orgId);
        regionAllotPlanVO.setIsDel(0);
        regionAllotPlanVO.setPlanStatus(planStatus);

        textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            log.warn("获取textGuid error，{}", regionAllotPlanVO);
            throw new Exception("系统异常：生产ID失败");
        }
        regionAllotPlanVO.setId(textResult.getValue());
        String planNo = genDocumentService.genDocumentNo(BillDesc.RegionAllotPlan, orgId);
        regionAllotPlanVO.setAllotPlanOrder(planNo);
        if(!StringUtils.isEmpty(sapCode)  && "2130".equals(sapCode)){

            regionAllotPlanVO.setCreateId("477477706045325312");
            regionAllotPlanVO.setCreateName("接口用户");
        }else{
            regionAllotPlanVO.setCreateId(userId);
            regionAllotPlanVO.setCreateName(commonService.getUserName(userId));
        }
        regionAllotPlanVO.setCreateDate(new Date());
        //新增
        regionAllotPlanMapper.insert(BeanUtil.do2bo(regionAllotPlanVO, RegionAllotPlanDO.class));

        for (RegionAllotPlanDetailVO detailVO : detailVOList) {
            textResult = fastGenClient.textGuid();
            if (textResult.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("系统异常：生产ID失败");
            }
            detailVO.setId(textResult.getValue());
            detailVO.setAllotPlanOrder(regionAllotPlanVO.getAllotPlanOrder());
            detailVO.setHeaderId(regionAllotPlanVO.getId());
            detailVO.setOrgId(regionAllotPlanVO.getOrgId());
            detailVO.setCreateDate(regionAllotPlanVO.getCreateDate());
            detailVO.setCreateId(regionAllotPlanVO.getCreateId());
            detailVO.setCreateName(regionAllotPlanVO.getCreateName());
            detailVO.setPlanStatus(regionAllotPlanVO.getPlanStatus());
            detailVO.setAllotAmount(BigDecimal.ZERO);
        }
        regionAllotPlanDetailService.deleteByFK(regionAllotPlanVO.getId());
        regionAllotPlanDetailService.batchAdd(BeanUtil.do2bo4List(detailVOList, RegionAllotPlanDetailDO.class));
        return planNo;
    }

    public RegionAllotPlanDO getAllotPlanByCrmOrder(String crmOrder){
        if(StringUtils.isEmpty(crmOrder)){
            return null;
        }
        List<RegionAllotPlanDO> allotPlans = regionAllotPlanMapper.findByCrmOrder(crmOrder);
        if(CollectionUtils.isEmpty(allotPlans)){
            return null;
        }
        return allotPlans.get(0);
    }


}
